package egovframework.npqs.pqi.mobile.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.PlaceOfficerActivity.OfficerListAdapter;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.ExportFruitSearchItem;
import egovframework.npqs.pqi.mobile.jsonparser.ExportFruitSearchThread;
import egovframework.npqs.pqi.mobile.jsonparser.PlaceOfficerThread;
import egovframework.npqs.pqi.mobile.jsonparser.ExportFruitSearchThread.ExportFruitSearchThreadCallback;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

//수출단지 선과장 검색
public class ExportFruitSearchActivity extends Activity implements ExportFruitSearchThreadCallback, OnItemSelectedListener{
	private TextView titleTxt, navigation;	// 상단 타이틀
	private AppStatus myapp;
	private String search;
	private Context context;
	private ExportFruitSearchAdapter fruitAdapter;
	private ExportFruitSearchThread fruitThread;
	private ProgressDialog dialog;
	private ArrayList<ExportFruitSearchItem> arrFruitItem;
	//컴포넌트
	private ListView listView;
	private EditText fruitPacking;
	private ImageButton searchBtn, btnHome, btn_exit;
	
	//스피너 담는 어레이
	private Spinner yearSpin;
	private ArrayAdapter<String> yearAdapter;
	private ArrayList<String> yearList;
	private String selectYear;
	
	
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("수출단지선과장검색");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_export_fruit_search);
		
		Intent intent = getIntent();
		search = intent.getStringExtra("search");
		
		init();
		
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) context.getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("수출단지선과장검색");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		
		listView = (ListView)findViewById(R.id.fruit_list);
		fruitPacking = (EditText)findViewById(R.id.inputText);
		yearSpin = (Spinner)findViewById(R.id.spinner);
		searchBtn = (ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				searchDataLoad();
			}
		});
		
		btn_exit = (ImageButton)findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				finish();
			}
		});
		
		fruitAdapter = new ExportFruitSearchAdapter();
		
		firstDateLoad();
		
	}
	
	public void setSpinerData(){
		if(arrFruitItem.size()>0){
			yearList = new ArrayList<String>();
			for(int i=0; i<arrFruitItem.size(); i++){
				yearList.add(arrFruitItem.get(i).getAppointYear());
			}
		}
		yearAdapter = new ArrayAdapter<String>(context,  R.layout.spinner_item, yearList);
		yearAdapter.setDropDownViewResource(R.layout.spinner_item);
		
		yearSpin.setAdapter(yearAdapter);
		yearSpin.setOnItemSelectedListener(this);
	}
	
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		switch (parent.getId()) {
		case R.id.spinner:
			//fruitPacking.setText(yearList.get(position).toString());
			Toast.makeText(context, position+"번째 클뤽 : "+yearList.get(position).toString(), Toast.LENGTH_SHORT).show();
			selectYear = yearList.get(position).toString();
			break;

		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}

	private void firstDateLoad(){
		String str="";
		String num="";
		if(!"".equals(search)|| null != search){
			if(Pattern.matches("^[0-9]+$", search)){
				//숫자면
				num = search;
			}else{
				//문자면
				str = search;
			}
		}
		Log.i("searchParam : ", "문자 : "+str+", 숫자 : "+num);
		
		fruitThread = new ExportFruitSearchThread(context, this, num, str );
		fruitThread.start();
		
		showDialogNo();
	}
	
	private void searchDataLoad(){
		fruitThread = new ExportFruitSearchThread(context, this, selectYear, fruitPacking.getText().toString());
		fruitThread.start();
		showDialogNo();
	}
	
	private void showDialogNo() {
		dialog = new ProgressDialog(ExportFruitSearchActivity.this);
		dialog.setMessage(context.getApplicationContext().getString(R.string.data_load));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
	}
	
	@Override
	public void OnExportFruitSearchCompleted(boolean isNetworkConntected,
			List<ExportFruitSearchItem> arrFruitItem) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}else{
			this.arrFruitItem = (ArrayList<ExportFruitSearchItem>) arrFruitItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnExportFruitSearchError(ErrorItem errorItem) {
		if(dialog !=null && dialog.isShowing()) {
			dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				
				fruitAdapter.notifyDataSetChanged();
				listView.setAdapter(fruitAdapter);
				setSpinerData();
				
				if(arrFruitItem.size() == 1){
					returnToActivity();
				}else{
					fruitAdapter.notifyDataSetChanged();
					listView.setAdapter(fruitAdapter);	
				}
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				myapp.utilm.ShowDialog(ExportFruitSearchActivity.this, "실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(context, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	private void returnToActivity(){
		search="";
		/*Intent intent = new Intent();
		intent.putExtra("userNm", myapp.getArrPlaceOfficerItem().get(0).getUserNm());
		intent.putExtra("userSn", myapp.getArrPlaceOfficerItem().get(0).getUserSn());
		intent.putExtra("allInsttNm", myapp.getArrPlaceOfficerItem().get(0).getAllInsttNm());
		
		setResult(1, intent);
		finish();*/
	}
	
	class ExportFruitSearchAdapter extends BaseAdapter {
		TextView division, fruitPacking, authortyIns, country, goodsName, selectYear, consAddrStr;

		@Override
		public int getCount() {
			Log.i("getCount", "getCount");
			return arrFruitItem.size();
		}

		@Override
		public Object getItem(int position) {
			Log.i("getItem", "getItem");
			return arrFruitItem.get(position);
		}

		@Override
		public long getItemId(int position) {
			Log.i("getItemId", "getItemId");
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_fruit_packing_item, parent, false);
    		}
			
			division = (TextView)convertView.findViewById(R.id.text_1_1);
			fruitPacking = (TextView)convertView.findViewById(R.id.text_2_1);
			authortyIns = (TextView)convertView.findViewById(R.id.text_3_1);
			country = (TextView)convertView.findViewById(R.id.text_4_1);
			goodsName = (TextView)convertView.findViewById(R.id.text_5_1);
			selectYear = (TextView)convertView.findViewById(R.id.text_6_1);
			consAddrStr = (TextView)convertView.findViewById(R.id.text_7_1);
			
			division.setText(arrFruitItem.get(position).getAreaNm());
			fruitPacking.setText(arrFruitItem.get(position).getKorNm());
			authortyIns.setText(arrFruitItem.get(position).getOffNm());
			country.setText(arrFruitItem.get(position).getCountryNm());
			goodsName.setText(arrFruitItem.get(position).getFruitNm());
			selectYear.setText(arrFruitItem.get(position).getAppointYear());
			consAddrStr.setText(arrFruitItem.get(position).getLnmAdres()+" "+arrFruitItem.get(position).getLnmAdresDetail());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			//arrFruitItem 안에 다 담겨있다.
			Intent intent = new Intent();
			intent.putExtra("exportAreaCd", arrFruitItem.get(position).getExportAreaCd());
			intent.putExtra("appointYear", arrFruitItem.get(position).getAppointYear());
			intent.putExtra("areaNm", arrFruitItem.get(position).getAreaNm());
			intent.putExtra("countryNm", arrFruitItem.get(position).getCountryNm());
			intent.putExtra("fruitNm", arrFruitItem.get(position).getFruitNm());
			intent.putExtra("korNm", arrFruitItem.get(position).getKorNm());
			intent.putExtra("offNm", arrFruitItem.get(position).getOffNm());
			intent.putExtra("zipcode", arrFruitItem.get(position).getZipcode());
			intent.putExtra("lnmAdres", arrFruitItem.get(position).getLnmAdres());
			intent.putExtra("lnmAdresDetail", arrFruitItem.get(position).getLnmAdresDetail());
			setResult(1, intent);
			finish();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}
	
}
